using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using CPlatePrintSys.Domain.DTOs;
using System.Windows.Documents;

namespace CPlatePrintSys.Application.Services
{
    /// <summary>
    /// AM系统图纸信息获取服务
    /// </summary>
    public class AmService
    {
        private bool _useLocalTestData = true;

        // 预留API或数据源地址字段
        private string _dataSource;
        public string DataSource
        {
            get => _dataSource;
            set => _dataSource = value;
        }

        public AmService(string dataSource = null)
        {
            _dataSource = dataSource;
        }

        /// <summary>
        /// 获取AM图纸信息（实际应为接口/文件读取，当前为mock数据）
        /// </summary>
        public async Task<List<AmDrawingInfoDto>> GetDrawingInfosAsync()
        {
            await Task.Delay(50); // 模拟异步
            var list = new List<AmDrawingInfoDto>();
            //for (int i = 1; i <= 25; i++)
            //{
            //    list.Add(new AmDrawingInfoDto
            //    {
            //        ShipNo = $"S{i:D3}",
            //        LotNo = $"L{i:D3}",
            //        PlateNo = $"P{i:D3}",
            //        Sequence = $"SEQ{i:D3}",
            //        DesignSpecCls = i % 2 == 0 ? "Q235B" : "Q345C",
            //        DesignSpecThickness = 10 + i % 5,
            //        DesignSpecLength = 8000 + i * 10,
            //        DesignSpecWidth = 2000 + i * 5,
            //        SdbPath = $@"D:\\AM\\S{i:D3}\\L{i:D3}\\P{i:D3}.sdb"
            //    });
            //}

            if (_useLocalTestData)
            {
                return LoadLocalMockData();
            }
            return list;
        }

        /// <summary>
        /// 从MockData文件夹加载本地数据
        /// </summary>
        public List<AmDrawingInfoDto> LoadLocalMockData()
        {
            try
            {
                // 获取应用程序所在目录
                string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
                
                // 构建MockData\AM\AMData.json的完整路径
                string mockDataPath = Path.Combine(appDirectory, "MockData", "AM", "AMData.json");
                
                // 检查文件是否存在
                if (!File.Exists(mockDataPath))
                {
                    throw new FileNotFoundException($"Mock数据文件未找到: {mockDataPath}");
                }
                
                // 读取JSON文件内容
                string jsonContent = File.ReadAllText(mockDataPath);
                
                // 反序列化为AmDrawingInfoDto列表
                var drawingInfos = JsonConvert.DeserializeObject<List<AmDrawingInfoDto>>(jsonContent);
                
                // 处理SdbPath路径
                foreach (var drawingInfo in drawingInfos)
                {
                    if (!string.IsNullOrEmpty(drawingInfo.SdbPath))
                    {
                        // 检查SdbPath是否为合法路径
                        if (!Path.IsPathRooted(drawingInfo.SdbPath) || !File.Exists(drawingInfo.SdbPath))
                        {
                            // 如果不是合法路径，则使用当前目录+文件名形成新的SdbPath
                            string fileName = Path.GetFileName(drawingInfo.SdbPath);
                            if (!string.IsNullOrEmpty(fileName))
                            {
                                drawingInfo.SdbPath = Path.Combine(appDirectory, "MockData", "AM", fileName);
                            }
                        }
                    }
                }
                
                return drawingInfos;
            }
            catch (Exception ex)
            {
                // 记录错误日志（这里可以根据需要添加日志记录）
                throw new InvalidOperationException($"加载本地Mock数据失败: {ex.Message}", ex);
            }
        }
    }
} 